# coding:utf-8

import pika

from common.rabbitmq_config import RABBIT_HOST, RABBIT_PASSWORD, RABBIT_USER_NAME


class RabbitMQ(object):
    """
    created by chenhj at 2017/7/25

    """
    def __init__(self):
        """
        created by chenhj at 2017/7/25

        """
        self.host = RABBIT_HOST
        self.credentials = (
            None if not (RABBIT_USER_NAME and RABBIT_PASSWORD)
            else pika.PlainCredentials(RABBIT_USER_NAME, RABBIT_PASSWORD)
        )
        self.connection = self.get_connection()

    def get_connection(self):
        """
        created by chenhj at 2017/7/25

        """
        return pika.BlockingConnection(pika.ConnectionParameters(
            host=RABBIT_HOST, credentials=self.credentials, heartbeat_interval=0
        ))

    def get_channel(self):
        """
        created by chenhj at 2017/7/25

        """
        if not self.connection.is_open:
            self.connection = self.get_connection()
        return self.connection.channel()
